import requests, json, re, time


class SfetyEducation():
    def __init__(self):
        self.category = 'https://weiban.mycourse.cn/pharos/usercourse/listCategory.do'
        self.courseUrl = 'https://weiban.mycourse.cn/pharos/usercourse/getCourseUrl.do'
        self.courseList = 'https://weiban.mycourse.cn/pharos/usercourse/listCourse.do'
        # userId
        self.userId = ''
        self.tenantCode = '4133010876'
        # token
        self.token = ''

    def getCategorys(self):
        data = {
            'userId': self.userId,
            'tenantCode': self.tenantCode,
            'token': self.token,
            'chooseType': 3,
            'userProjectId': '755675c3-617c-4fe8-9e6a-93d54b81c67b'
        }
        res = requests.post(self.category, data=data, verify=False)
        resj = json.loads(res.text)
        items = resj['data']
        print(items)
        for item in items:
            if item['totalNum'] == item['finishedNum']:
                print('完成')
                continue
            self.getCourses(item['categoryCode'])
    def getCourses(self, categoryCode):
        data = {
            'categoryCode': categoryCode,
            'tenantCode': self.tenantCode,
            'userId': self.userId,
            'token': self.token,
            'chooseType': 3,
            'userProjectId': '755675c3-617c-4fe8-9e6a-93d54b81c67b'
        }
        res = requests.post(self.courseList, data=data, verify=False)
        resj = json.loads(res.text)
        items = resj['data']
        for item in items:
            if item['finished'] == 1:
                print('完成项')
                continue
            data['courseId'] = item['resourceId']
            requests.post('https://weiban.mycourse.cn/pharos/usercourse/study.do', data=data, verify=False)
            self.getCourseUrl(item['resourceId'])

    def getCourseUrl(self, courseId):
        data = {
            'courseId': courseId,
            'tenantCode': self.tenantCode,
            'userId': self.userId,
            'token': self.token,
            'chooseType': 3,
            'userProjectId': '755675c3-617c-4fe8-9e6a-93d54b81c67b'
        }
        res = requests.post(self.courseUrl, data=data, verify=False)
        resj = json.loads(res.text)
        print(resj)
        referer = resj['data']
        self.finish(referer)

    def finish(self, referer):
        params = re.search("\?.+", referer).group() + '&callback=jQuery164047975117785661636&_1599287334149'
        print(params)
        headers = {
            'referer': referer
        }
        res = requests.get('https://weiban.mycourse.cn/pharos/usercourse/finish.do' + params, headers=headers,
                           verify=False)
        if '"msg":"ok"' in res.text:
            print('成功')
        else:
            print('失败')


a = SfetyEducation()
a.getCategorys()
